from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
import os, datetime, json

class ChatAction :
	def comment_total() :
		return MessageData.objects.count()

	def chat(time_update, session) :
		'如果没有content'
		qry = MessageData.objects.filter(time_create__gte=time_update, 
			session=session).order_by('time_create')
		chat_list = []
		for i in qry :	
			chat_list += [{
				'uuid': i.sender_uuid, 
				'nickname': i.sender_name, 
				'content': i.content, 
				'time_update': ChatAction.datetime_find(i.time_create), 
			}]
		return chat_list

	def datetime_find(time) :
		'返回简短时间'
		time += datetime.timedelta(0,8*3600,0)
		mon = int(time.strftime('%m'))
		day = int(time.strftime('%d'))
		date_string = "%d月%d日 " % (mon, day)
		time_string = time.strftime('%H:%M')
		return date_string + time_string

	def dict_render(request) :
		return {
			'request': request, 
			'nickname': request.session.get('nickname', ''), 
			'uuid': request.session.get('uuid', '')
		}

	def session_certify(request, session) :
		'用户是否可以访问session'
		if not session :
			return True
		if request.session('session-%s' % session, '') == 'True' :
			return True
		else :
			return False

class ChatViews :
	def message(request) :
		'接受投递message[POST]'
		nickname = request.session.get('nickname', '')
		suid = request.POST.get('uuid', '')
		request.session['uuid'] = suid
		content = request.POST.get('content', '')
		session = request.POST.get('session', '')
		if not ChatAction.session_certify(request, session) :
			return HttpResponseRedirect('/')
		if not suid or not content :
			return HttpResponseRedirect('/nickname/')
		if not nickname :
			nickname = uuid[0:8]
		MessageData(sender_name=nickname, content=content, sender_uuid=suid, 
					session=session).save()
		return HttpResponse('success: congradulations')

	def nickname(request) :
		'更改nickname'
		dict_render = ChatAction.dict_render(request)
		if request.session.get('nickname', '') :
			return HttpResponseRedirect('/')
		if request.method == 'POST' :
			request.session['nickname'] = request.POST.get('nickname', '');
			return HttpResponseRedirect('/')
		else :
			return render_to_response('nickname.html', dict_render, 
					context_instance=RequestContext(request))

	def chat(request, session='') :
		'返回网页[GET] 和 message[POST]'
		dict_render = ChatAction.dict_render(request)
		dict_render['session'] = session
		if not request.session.get('nickname', '') :
			return HttpResponseRedirect('/message/')
		if not ChatAction.session_certify(request, session) :
			return HttpResponseRedirect('/')
		if request.method == 'POST' :
			float_update = request.POST.get('time_update', '')
			time_update = datetime.datetime.fromtimestamp(float(float_update))
			message_list = ChatAction.chat(time_update, session)
			time_current = datetime.datetime.now()
			current_stamp = time_current.timestamp()
			result = json.dumps({
				'message_list': message_list, 
				'time_update': current_stamp, 
			})
			return HttpResponse(result, content_type="application/json")
		else:
			return render_to_response('comment.html', dict_render, 
					context_instance=RequestContext(request))

	def session(request) :
		'切换session'
		dict_render = ChatAction.dict_render(request)
		if request.method == 'POST' :
			session = request.POST.get('session', '')
			token = request.POST.get('token', '')
			dict_render['session'] = session
			dict_render['token'] = token
			if session :
				qry = SessionInfo.objects.filter(name=session)
				if qry :
					if qry[0].token == token or \
						ChatAction.session_certify(request, session) :
						request.session['session-%s' % session] = 'True'
					else :
						dict_render['content'] = 'Token 不正确'
						return render_to_response('session.html', dict_render, 
								context_instance=RequestContext(request))
				else :
					if len(token) < 4 or len(token) > 10 :
						dict_render['content'] = 'Token 长度不对（应该至少4位）'
						return render_to_response('session.html', dict_render, 
								context_instance=RequestContext(request))
					if not (0 <= len(session) <= 40) :
						dict_render['content'] = 'Session 太长'
						return render_to_response('session.html', dict_render, 
								context_instance=RequestContext(request))
					for i in session + token :
						if i not in '-0123456789' + \
							'abcdefghijklmnopqrstuvwxyz' + \
							'ABCDEFGHIJKLMNOPQRSTUVWXYZ' :
							dict_render['content'] = '包含非法字符'
							return render_to_response('session.html', dict_render, 
									context_instance=RequestContext(request))
					SessionInfo(name=session, token=token).save()
					request.session['session-%s' % session] = 'True'
				return HttpResponseRedirect('/s/%s/' % session)
			else :	# session == ''
				return HttpResponseRedirect('/')
		return render_to_response('session.html', dict_render, 
					context_instance=RequestContext(request))

